﻿using System;

namespace CustomerContactSystem.WebForms
{
    public partial class Login : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void LoginUserClick(object sender, EventArgs e)
        {
            if (!IsValidLogin()) {
                return;
            }
            var user = UserRepository.QueryOver().Where(u => u.Username == Username.Text).SingleOrDefault();
            if (user == null) {
                ErrorMsg.Text = "Username not found!";
            } else if (user.Password != Password.Text) {
                ErrorMsg.Text = "Invalid Password!";
            } else if (!user.IsActive) {
                ErrorMsg.Text = "You login has been deactivated. Contact IT Support!";
            }
            else {
                AddUserToSession(user.Id);
                if ((Request.QueryString["return"] != null))
                {
                    var retUrl = Request.QueryString["return"];
                    var qStr = "";
                    if ((Request.QueryString["querystring"] != null))
                    {
                        qStr = "?" + Request.QueryString["querystring"].Replace("|", "&").Replace("@", "=");
                    }
                    Response.Redirect(retUrl + qStr);
                }
                else
                {
                    Response.Redirect("~/Enquiries/Search.aspx");
                }
            }
        }

        private bool IsValidLogin() {
            if (string.IsNullOrEmpty(Username.Text)) {
                ErrorMsg.Text = "Username is required!";
                return false;
            }

            if (string.IsNullOrEmpty(Password.Text)) {
                ErrorMsg.Text = "Password is required!";
                return false;
            }
            return true;
        }
    }
}